import { Component } from '@angular/core';

import { Hero } from './hero';

@Component({
  selector: 'app-hero-form',
  templateUrl: './hero-form.component.html',
  styleUrls: [ './hero-form.component.css' ]
})
export class HeroFormComponent {

  powers = ['Really Smart', 'Super Flexible',
    'Super Hot', 'Weather Changer'];

  model = new Hero(18, 'Dr IQ', this.powers[0], 'Chuck Overstreet');

  submitted = false;

  onSubmit() { this.submitted = true; }

  newHero() {
    this.model = new Hero(42, '', '');
  }

  testPromise() {
    this.runAsync1()
      .then(data => {
        console.log(data);
        return this.runAsync2();
      })
      .then(data => {
        console.log(data);
        return this.runAsync3();
      })
      .then(data => {
        console.log(data);
        return '不做异步操作';
      })
      .then(data => console.log(data));
  }

  testBreakPromiseChain() {
    this.runAsync1()
      .then(data => {
        console.log(data);
        return Promise.reject({
          notRealPromiseException: true,
        });
      })
      .then(data => {
        console.log(data);
        return this.runAsync3();
      })
      .catch(ex => {
        console.log('ex: ', ex);
        if (ex.notRealPromiseException) {
          console.log('处理执行runAsync1后的中断');
        } else {
          console.log('真正的异常');
        }
      });
  }

  private runAsync1(): any {
    let p = new Promise(function(resolve, reject){
      setTimeout(function(){
        console.log('异步任务1执行完成');
        resolve('随便什么数据1');
      }, 2000);
    });
    return p;
  }

  private runAsync2(): any {
    let p = new Promise(function(resolve, reject){
      setTimeout(function(){
        console.log('异步任务2执行完成');
        resolve('随便什么数据2');
      }, 2000);
    });
    return p;
  }

  private runAsync3(): any {
    let p = new Promise(function(resolve, reject){
      setTimeout(function(){
        console.log('异步任务3执行完成');
        resolve('随便什么数据3');
      }, 2000);
    });
    return p;
  }

  testReject() {
    this.getNumber()
      .then(data => {
        console.log('resolved');
        console.log(data);
        // 未定义，在catch中处理
        //console.log(somedata);
      }, reason => {
        console.log('rejected');
        console.log(reason);
      })
      .catch(reason => {
        console.log('rejected');
        console.log(reason);
      });
  }

  private getNumber() {
    let p = new Promise(function(resolve, reject){
      setTimeout(function(){
        let num = Math.ceil(Math.random() * 10);
        if (num <= 5) {
          resolve(num);
        } else {
          reject('数字太大了');
        }
      }, 2000);
    });
    return p;
  }

  // TODO: Remove this when we're done
  get diagnostic() { return JSON.stringify(this.model); }
}
